package com.cyt.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.sys.model.po.SysVersion;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.BaseUtil;
import com.cyt.base.util.DateUtil;
import com.cyt.base.util.ErrorCode;
import com.cyt.base.util.httpclient.HttpUtilNew;
import com.cyt.sys.dao.SysLisenceManageDao;
import com.cyt.sys.dao.SysVersionDao;
import com.cyt.sys.model.po.SysLisenceManage;
import com.cyt.sys.model.vo.SysLisenceManageVo;
import com.cyt.sys.service.SysAppModuleService;
import com.cyt.sys.service.SysLisenceManageService;
import com.cyt.sys.service.SysVersionService;
import com.cyt.sys.util.EntryUtils;
import com.cyt.sys.util.Md5Base64;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 *@Author: dingxu
 *@Date: 2019-04-03 8:19
 *@Description:lisence管理service实现类
 */
@Service("baseLisenceManageService")
public class SysLisenceManageServiceImpl extends BaseServiceImpl<SysLisenceManage> implements SysLisenceManageService {


    private static String LISENCE_SUCCESS_VALUE="lisence信息加密成功";
    private static String LISENCE_FAIL_VALUE="lisence信息加密失败";
    private static String SEND_DATA_URL="/api/baseLisenceManage/receive";


    @Autowired
    private SysVersionDao sysVersionDao;
    @Resource
    private SysLisenceManageDao sysLisenceManageDao;
    @Resource
    private SysVersionService sysVersionService;
    @Resource
    private SysAppModuleService sysAppModuleService;
    @Autowired
    public void setBaseDao(SysLisenceManageDao sysLisenceManageDao) {
        this.baseDao = sysLisenceManageDao;
    }

    /**
     * lisence分页查询接口
     *
     * @param sysLisenceManageVo 对象
     * @param pageSize 第几页
     * @param pageNum 每页数量
     * @return ReturnResult 对象
     * @author dingxu
     * @date 2019-04-04 14:25
     */
    @Override
    public ReturnResult page(SysLisenceManageVo sysLisenceManageVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" create_time desc");
        Example example = new Example(SysLisenceManage.class);
        Example.Criteria criteria = example.createCriteria();
        if(com.github.pagehelper.StringUtil.isNotEmpty(sysLisenceManageVo.getUserInfo())){
            criteria.andLike("userInfo","%"+ sysLisenceManageVo.getUserInfo()+"%");
        }
        List<SysLisenceManage> list= sysLisenceManageDao.selectByExample(example);
        PageInfo<SysLisenceManage> page=new PageInfo<SysLisenceManage>(list);
        Map<String,Object> map=new HashedMap();
        map.put("page",page.getList());
        return new ReturnResult(page.getList(),page.getTotal(),page.isHasNextPage());
    }



    /**
     * 添加修改lisence信息
     *
     *@author dingxu
     *@date 2019-04-04 14:25
     *@param sysLisenceManageVo 对象
     *@return ReturnResult
     */
    @Override
    public ReturnResult addOrUpdate(SysLisenceManageVo sysLisenceManageVo) {
        if (sysLisenceManageVo.getId() == null || "".equals(sysLisenceManageVo.getId())) {

            SysVersion version = sysVersionDao.selectByPrimaryKey(sysLisenceManageVo.getVersonId());

            SysLisenceManage baseLisenceManage = new SysLisenceManage();
            baseLisenceManage.setId(BaseUtil.uId());
            baseLisenceManage.setDownTime(sysLisenceManageVo.getDownTime());
            baseLisenceManage.setDescription(sysLisenceManageVo.getDescription());
            baseLisenceManage.setLisence(sysLisenceManageVo.getLisence());
            baseLisenceManage.setStatus(sysLisenceManageVo.getStatus());
            baseLisenceManage.setType(sysLisenceManageVo.getType());
            baseLisenceManage.setCreateTime(new Date());
            baseLisenceManage.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
            baseLisenceManage.setPersonNum(sysLisenceManageVo.getPersonNum());
            baseLisenceManage.setUserInfo(sysLisenceManageVo.getUserInfo());
            baseLisenceManage.setVersonId(sysLisenceManageVo.getVersonId());
            baseLisenceManage.setMacAddress(sysLisenceManageVo.getMacAddress());
            baseLisenceManage.setUrl(sysLisenceManageVo.getUrl());
            baseLisenceManage.setValidTime(sysLisenceManageVo.getValidTime());
            baseLisenceManage.setVersonNumber(version.getVersionNumber());
            int id = sysLisenceManageDao.insert(baseLisenceManage);
            if (id <= 0) {
                return new ReturnResult(BaseConstant.DATABASE_ERROR_INSERT);
            }
        } else {
            SysLisenceManage baseLisenceManage = sysLisenceManageDao.selectByPrimaryKey(sysLisenceManageVo.getId());
            if(StringUtil.isNotEmpty(sysLisenceManageVo.getVersonId())){
                SysVersion version = sysVersionDao.selectByPrimaryKey(sysLisenceManageVo.getVersonId());
                baseLisenceManage.setVersonNumber(version.getVersionNumber());
            }else{
                baseLisenceManage.setVersonNumber(sysLisenceManageVo.getVersonNumber());
            }
            baseLisenceManage.setDownTime(sysLisenceManageVo.getDownTime());
            baseLisenceManage.setDescription(sysLisenceManageVo.getDescription());
            baseLisenceManage.setLisence(sysLisenceManageVo.getLisence());
            baseLisenceManage.setStatus(sysLisenceManageVo.getStatus());
            baseLisenceManage.setType(sysLisenceManageVo.getType());
            baseLisenceManage.setCreateTime(new Date());
            baseLisenceManage.setPersonNum(sysLisenceManageVo.getPersonNum());
            baseLisenceManage.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
            baseLisenceManage.setMacAddress(sysLisenceManageVo.getMacAddress());
            baseLisenceManage.setUrl(sysLisenceManageVo.getUrl());
            baseLisenceManage.setUserInfo(sysLisenceManageVo.getUserInfo());
            baseLisenceManage.setVersonId(sysLisenceManageVo.getVersonId());
            baseLisenceManage.setValidTime(sysLisenceManageVo.getValidTime());
            int id = sysLisenceManageDao.updateByPrimaryKey(baseLisenceManage);
            if (id <= 0) {
                return new ReturnResult(BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
        return new ReturnResult(BaseConstant.DATABASE_SUCCEED_MSG);
    }


    /**
     * 删除lisence信息
     *
     *@author dingxu
     *@date 2019-04-04 14:25
     *@param ids id数组集字符串
     *@return ReturnResult
     */

    public ReturnResult delete(String ids) {
        String[] idList=ids.split(",");
        boolean flage=true;
        StringBuffer stringBuffer=new StringBuffer();
        for (String id:idList){
            SysLisenceManage baseLisenceManage = sysLisenceManageDao.selectByPrimaryKey(id);
            int num= sysLisenceManageDao.delete(baseLisenceManage);
            if(num>0){
                flage=true;
            }else{
                stringBuffer.append("");
            }
        }
        if(flage){
            return new ReturnResult();
        }else{
            return new ReturnResult(ErrorCode.CODE_101_MSG);
        }
    }

    /**
     * 下发lisence
     *
     * @author dingxu
     * @date 2019-04-02 14:25
     * @param id 主键id字符串数组集
     * @return ReturnResult
     */
    @Override
    public ReturnResult sendLisence(String id) {
        SysLisenceManage baseLisenceManage= sysLisenceManageDao.selectByPrimaryKey(id);
        SysLisenceManageVo sysLisenceManageVo =new SysLisenceManageVo();
        EntryUtils.copyProperties(baseLisenceManage, sysLisenceManageVo);
        sysLisenceManageVo.setCreateTimeStr(DateUtil.convertDateToString(DateUtil.DATE_TIME_PATTERN, sysLisenceManageVo.getCreateTime()));
        sysLisenceManageVo.setDownTimeStr(DateUtil.convertDateToString(DateUtil.DATE_TIME_PATTERN, sysLisenceManageVo.getDownTime()));
        sysLisenceManageVo.setUpdateTimeStr(DateUtil.convertDateToString(DateUtil.DATE_TIME_PATTERN, sysLisenceManageVo.getUpdateTime()));
        sysLisenceManageVo.setDownTime(null);
        sysLisenceManageVo.setUpdateTime(null);
        sysLisenceManageVo.setCreateTime(null);
        Map<String,Object> lisence=BeanUtil.beanToMap(sysLisenceManageVo);
        Map<String, String> params = JSONObject.parseObject(JSON.toJSONString(lisence), new TypeReference<Map<String, String>>(){});
        String post= HttpUtilNew.sendPost(baseLisenceManage.getUrl()+SEND_DATA_URL,params);
        sysVersionService.sendVersion(baseLisenceManage.getUrl(), sysLisenceManageVo.getId());
        sysAppModuleService.sendApply(baseLisenceManage.getUrl(), sysLisenceManageVo.getId());
        Map<String,Object> maps = (Map<String,Object>) JSON.parse(post);
        Integer code=Integer.parseInt(maps.get("code").toString());
        if(code==0){
            return new ReturnResult(BaseConstant.DATABASE_SEND_SUCCESSD);
        }
        return new ReturnResult(BaseConstant.DATABASE_SEND_ERROR);
    }

    /**
     * 对lisence进行加密处理
     *
     * @author sunli
     * @Date 2019-04-16
     * @param lisenceId
     */
    @Override
    public ReturnResult encordBaseLisence(String lisenceId) {

        SysLisenceManage baseLisenceManage= sysLisenceManageDao.selectByPrimaryKey(lisenceId);
        String versionId=baseLisenceManage.getVersonId();
        //拼接前缀
        String uuid= UUID.randomUUID().toString();
        String headContent= uuid.substring(0,4)+baseLisenceManage.getType()+",";
        //调用加密方法
        String encryptLisence= Md5Base64.encryptMd5BASE64(headContent,versionId);
        //对加密的字符串进行处理
        String NewEncryptLisence=uuid.toUpperCase().substring(0,8)+encryptLisence.replace("="," ");
        baseLisenceManage.setLisence(NewEncryptLisence);
        sysLisenceManageDao.updateByPrimaryKey(baseLisenceManage);
        //String getVersionId=Md5Base64.decryptBASE64(NewEncryptLisence);

        if(StringUtil.isNotEmpty(encryptLisence)){
            return new ReturnResult(LISENCE_SUCCESS_VALUE);
        }else{
            return new ReturnResult(LISENCE_FAIL_VALUE);
        }
    }

}